package org.bling.star.client.server.send.impl;

import org.bling.star.client.connect.ClientConnection;

import org.bling.star.client.server.send.ConnectService;
import org.bling.star.client.server.send.UserService;
import org.bling.star.common.command.*;
import org.bling.star.common.enums.BusinessCommandType;
import org.bling.star.common.response.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ConnectServiceImpl implements ConnectService {

    private final ConfigurableApplicationContext configurableApplicationContext;
    private final ClientConnection clientConnection;
    private final UserService userService;
    public ConnectServiceImpl(ClientConnection clientConnection, UserService userService,ConfigurableApplicationContext configurableApplicationContext) {
        this.clientConnection = clientConnection;
        this.userService = userService;
        this.configurableApplicationContext = configurableApplicationContext;
    }

    @Override
    public BaseResponse createTalkingPool() {
        CreateCommand createCommand = new CreateCommand();
        createCommand.setCommandType(BusinessCommandType.POOL_CREATE_POOL);
        createCommand.setUserInfo(userService.getUserInfo());
        BaseResponse send = clientConnection.send(createCommand);
        log.info(send.toString());
        return send;
    }

    @Override
    public BaseResponse join(JoinCommand joinRequest) {
        joinRequest.setCommandType(BusinessCommandType.POOL_JOIN_POOL);
        joinRequest.setUserInfo(userService.getUserInfo());
        BaseResponse send = clientConnection.send(joinRequest);
        log.info(send.toString());
        return send;
    }

    @Override
    public BaseResponse talking(TalkingCommand talkingRequest) {
        talkingRequest.setCommandType(BusinessCommandType.POOL_TALKING);
        talkingRequest.setUserInfo(userService.getUserInfo());
        talkingRequest.setMessage("hello world");
        BaseResponse send = clientConnection.send(talkingRequest);
        return send;
    }

    @Override
    public void exit(ExitCommand exitCommand) {
        exitCommand.setCommandType(BusinessCommandType.POOL_EXIT);
        clientConnection.send(exitCommand);
    }

    @Override
    public void disconnect(DisConnectCommand disConnectCommand) {
        clientConnection.send(disConnectCommand);
    }

    @Override
    public void close() {

        boolean close = clientConnection.close();
        if(close) {
            configurableApplicationContext.close();
        }
    }
}
